﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.IMSC.Model.DbModels.LowPriceHouse;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.API
{
    [Description("API-账户")]
    [ApiAuthentication]
    public class LowPriceHousesController : BaseApiController
    {
        public ILowPriceHouseRunningsContract LowPriceHouseRunningsContract { get; set; }
        public ILowPriceHousesContract LowPriceHousesContract { get; set; }
        public IImagesContract ImagesContract { get; set; }
        public IAreaContract AreaContract { get; set; }
        public IUsersContract UsersContract { set; get; }
        public ICustomerContract CustomerContract { get; set; }
        public ICustomerPhoneContract CustomerPhoneContract { get; set; }
        public IIntermediaryContract IntermediaryContract { get; set; }
        public IIntermediaryStaffContract IntermediaryStaffContract { get; set; }
        public IBrokerageRunningsContract BrokerageRunningsContract { get; set; }
        public IBrokerageSettleAccountsRunningsContract BrokerageSettleAccountsRunningsContract { get; set; }
        public IDictionaryContract DictionaryContract { set; get; }
        public IMessageBoardsContract MessageBoardsContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public ILowPriceHouseBuildingsContract LowPriceHouseBuildingsContract { get; set; }
        public IBuildingTopContract BuildingTopContract { get; set; }




        //低价房条件====================================================================================================

        [Description("API-低价房条件")]
        public IHttpActionResult ttGetLowPriceHousesCondition()
        {

            var HouseType = DictionaryContract.Entities.Where(d => d.Name == "ResidenceType").ToList();//户型
            var BuildingsType = DictionaryContract.Entities.Where(d => d.Name == "BuildingsType").ToList();//房屋类型
            var DecorationCondition = DictionaryContract.Entities.Where(d => d.Name == "DecorationCondition").ToList();//装修情况


            LowPriceHousesConditionModel dcc = new LowPriceHousesConditionModel();

            dcc.HouseType = HouseType == null ? new List<Dictionary>() : HouseType;
            dcc.BuildingsType = BuildingsType == null ? new List<Dictionary>() : BuildingsType;
            dcc.DecorationCondition = DecorationCondition == null ? new List<Dictionary>() : DecorationCondition;


            var result = new AjaxResult("成功", AjaxResultType.Success, dcc);

            return Token(result, "");

        }


        //低价房====================================================================================================

        [Description("API-低价房列表")]
        public IHttpActionResult ttGetBuildingsList([FromBody]LowPriceHousesParamsModel entity)
        {

            if (entity.BuildingsTypeVal == "住宅")
            {
                if (entity.LowHouseType == 0)
                {
                    entity.LowHouseType = 1;
                }
                entity.BuildingsTypeVal = "";
            }
            else if (entity.BuildingsTypeVal == "商业")
            {
                if (entity.LowHouseType == 0)
                {
                    entity.LowHouseType = 3;
                }
                entity.BuildingsTypeVal = "";
            }


            //获取UserID
            int userid = BaseWebApiExt.GetUserIDByToken();

            //获取相关信息
            var userModel = UsersContract.GetByKey(userid);//经纪人

            var query = from a in LowPriceHousesContract.Entities
                        join b in LowPriceHouseBuildingsContract.Entities on a.LowPriceHouseBuildingID equals b.Id
                        where (!a.IsDeleted && a.State==1 &&(entity.GroupID == 2 ? 2 : 1)==a.GroupID && b.CityID==userModel.CityID)
                        select new
                        {
                            AgentID = a.AgentID,
                            Area = a.Area,
                            AreaID = b.AreaID,
                            AwardDescription = a.AwardDescription,
                            BalconyNumber = a.BalconyNumber,
                            BandSawBrokerage = a.BandSawBrokerage,
                            BrandAdvantage = b.BrandAdvantage,
                            Brokerage = a.Brokerage,
                            BuildingClass = a.BuildingClass,
                            BuildingsType = a.BuildingsType,
                            CarNumber = b.CarNumber,
                            Characteristic = b.Characteristic,
                            CityID = b.CityID,
                            CommissionAccount = a.CommissionAccount,
                            CookNumber = a.CookNumber,
                            CostPrice = a.CostPrice,
                            CoveredArea = b.CoveredArea,
                            CreatedTime = a.CreatedTime,
                            CreateYear = a.CreateYear,
                            DecorationCondition = a.DecorationCondition,
                            Developer = b.Developer,
                            DeveloperBrand = b.DeveloperBrand,
                            DownPaymentRate = a.DownPaymentRate,
                            GreeningRatio = b.GreeningRatio,
                            HallNumber = a.HallNumber,
                            HaveProductComparison = b.HaveProductComparison,
                            HouseNumber = a.HouseNumber,
                            HouseType = a.HouseType,
                            HouseTypeArea = b.HouseTypeArea,
                            HouseTypeRemark = a.HouseTypeRemark,
                            Id = a.Id,
                            Installation = a.Installation,
                            IsDeleted = a.IsDeleted,
                            IsLoan = a.IsLoan,
                            IsLocked = a.IsLocked,
                            LaunchTime = b.LaunchTime,
                            LivingFacilities = b.LivingFacilities,
                            LoanRules = a.LoanRules,

                            LowHouseType = a.LowHouseType,
                            GroupID = a.GroupID,

                            LowPrice = a.LowPrice,
                            LowPriceHouseBuildingID = a.LowPriceHouseBuildingID,
                            BuildingName = b.Name,
                            BuildingAddress = b.Address,
                            MediumOfCommunicationStaffID = a.MediumOfCommunicationStaffID,
                            Nature = a.Nature,
                            NegotiatedPrice = a.NegotiatedPrice,
                            OpeningTime = b.OpeningTime,
                            Orientations = a.Orientations,
                            OwnerID = a.OwnerID,
                            ParkingRatio = b.ParkingRatio,
                            PlotRatio = b.PlotRatio,
                            Poundage = a.Poundage,
                            PriceAdvantage = b.PriceAdvantage,
                            PriceCondition = a.PriceCondition,
                            PropertyManagementCompany = b.PropertyManagementCompany,
                            PropertyManagementFee = b.PropertyManagementFee,
                            PropertyRight = a.PropertyRight,
                            PropertyType = a.PropertyType,
                            ProvinceID = b.ProvinceID,
                            RegionalDevelopment = b.RegionalDevelopment,
                            Remark = a.Remark,
                            ReNameDeadline = a.ReNameDeadline,
                            ResidenceType = a.ResidenceType,
                            RoomNumber = a.RoomNumber,
                            Rules = a.Rules,
                            SchoolDistrict = b.SchoolDistrict,
                            ShowIndex = a.ShowIndex,
                            StarTarget = a.StarTarget,
                            StarTargetRemark = a.StarTargetRemark,
                            State = a.State,
                            StationedStaffID = a.StationedStaffID,
                            Storey = a.Storey,
                            ToiletNumber = a.ToiletNumber,
                            TotalHouseholds = b.TotalHouseholds,
                            TotalStorey = a.TotalStorey,
                            Transportation = b.Transportation,
                            UseArea = a.UseArea,
                            X = b.X,
                            Y = b.Y

                        };

            //低价房类型
            if (entity.LowHouseType==1)
            {
                query = query.Where(p => p.LowHouseType == 1);
            }
            else if (entity.LowHouseType == 2)
            {
                query = query.Where(p => p.LowHouseType == 2);
            }
            else if (entity.LowHouseType == 3)
            {
                query = query.Where(p => p.LowHouseType == 3 || p.LowHouseType == 4);
            }
            else if (entity.LowHouseType == 4)
            {
                query = query.Where(p => p.LowHouseType == 3 || p.LowHouseType == 4);
            }

            //低价房分组
            if (entity.GroupID == 1)
            {
                query = query.Where(p => p.GroupID == 1);
            }
            else if (entity.GroupID == 2)
            {
                query = query.Where(p => p.GroupID == 2);
            }

            //条件搜索
            if (!string.IsNullOrWhiteSpace(entity.KeyWord))
            {
                query = query.Where(m => m.BuildingName.Contains(entity.KeyWord));
            }

            //区域
            if (!string.IsNullOrWhiteSpace(entity.AreaID))
            {
                query = query.Where(m => m.AreaID.Equals(entity.AreaID));
            }

            //下拉框条件============================================

            //户型
            if (!string.IsNullOrWhiteSpace(entity.HouseTypeVal))
            {
                query = query.Where(m => m.ResidenceType == entity.HouseTypeVal);
            }

            //房屋类型
            if (!string.IsNullOrWhiteSpace(entity.BuildingsTypeVal))
            {
                query = query.Where(m => m.BuildingsType == entity.BuildingsTypeVal);
            }

            //装修状况
            if (!string.IsNullOrWhiteSpace(entity.DecorationConditionVal))
            {
                query = query.Where(m => m.DecorationCondition == entity.DecorationConditionVal);
            }

            //文本条件============================================

            //面积
            double areaMin = -1;
            double areaMax = -1;
            ConvertToIntExt(entity.AreaMin, entity.AreaMax, out areaMin, out areaMax);
            if(areaMin > -1)
            {
                query = query.Where(m => m.Area >= (decimal)areaMin);
            }
            if (areaMax > -1)
            {
                query = query.Where(m => m.Area <= (decimal)areaMax);
            }

            //楼层
            double storeyMin = -1;
            double storeyMax = -1;
            ConvertToIntExt(entity.StoreyMin, entity.StoreyMax, out storeyMin, out storeyMax);
            if (storeyMin > -1)
            {
                query = query.Where(m => m.Storey >= (int)storeyMin);
            }
            if (storeyMax > -1)
            {
                query = query.Where(m => m.Storey <= (int)storeyMax);
            }

            //年代
            double createYearMin = -1;
            double createYearMax = -1;
            ConvertToIntExt(entity.CreateYearMin, entity.CreateYearMax, out createYearMin, out createYearMax);
            if (createYearMin > -1)
            {
                query = query.Where(m => Convert.ToInt32(m.CreateYear) >= (int)createYearMin);
            }
            if (createYearMax > -1)
            {
                query = query.Where(m => Convert.ToInt32(m.CreateYear) <= (int)createYearMax);
            }

            //价格
            double priceMin = -1;
            double priceMax = -1;
            ConvertToIntExt(entity.PriceMin, entity.PriceMax, out priceMin, out priceMax);
            if (priceMin > -1)
            {
                query = query.Where(m => m.LowPrice >= (decimal)priceMin * 10000);
            }
            if (priceMax > -1)
            {
                query = query.Where(m => m.LowPrice <= (decimal)priceMax * 10000);
            }


            var list = (from m in query
                        //join n in BuildingTopContract.Entities on m.Id equals n.UnionID into tempb
                        //from b in tempb.DefaultIfEmpty()

                        //where (b != null && b.UnionModule == (entity.GroupID + 1) && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted) //低价房/共享房
                        //|| b == null //没有置顶

                        let img = (from m1 in ImagesContract.Entities where m1.GroupID == 4 && m1.InterfixID == m.Id && m1.IsDeleted == false orderby m1.Id select (m1.ImagePath + m1.FileName)).FirstOrDefault()

                        select new LowPriceHousesListModel
                        {
                            Id = m.Id,
                            BuildingName = m.BuildingName,
                            CostPrice = m.CostPrice+"",//原价
                            LowPrice = m.LowPrice+"",//底价
                            Area = m.Area + "㎡",//面积
                            IsLoan = m.IsLoan == 1 ? "可以贷款" : "不可贷款",
                            Poundage = m.Poundage,//订金
                            Brokerage = m.Brokerage,//佣金
                            CommissionAccount = m.CommissionAccount,//佣金帐期
                            ImagePath = (img == null) ? "" : img.Replace(@"\", "/"),
                            CreatedTime = m.CreatedTime,

                            IsTop = BuildingTopContract.Entities.Count(b => b.UnionModule == entity.GroupID+1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted && b.UnionID == m.Id),//是否置顶
                            TopShowIndex = BuildingTopContract.Entities.Count(b => b.UnionModule == entity.GroupID+1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted && b.UnionID == m.Id) == 0 ? m.ShowIndex : BuildingTopContract.Entities.FirstOrDefault(b => b.UnionModule == 1 && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted && b.UnionID == m.Id).ShowIndex,
                            //IsTop = b == null ? 0 : 1,//是否置顶
                            //TopShowIndex = b == null ? 0 : b.ShowIndex,
                        });

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(x => x.IsTop).ThenBy(m => m.TopShowIndex).ThenByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<LowPriceHousesListModel>().AsQueryable();// null;

            List<LowPriceHousesListModel> l = list.ToList();
            foreach (var item in l)
            {
                item.CostPrice = (Convert.ToDecimal(item.CostPrice) / 10000m).ToString("F2") + "万元";
                item.LowPrice = (Convert.ToDecimal(item.LowPrice) / 10000m).ToString("F2") + "万元";
            }

            var result = new AjaxResultRow("成功", AjaxResultType.Success, l, total);
            return Token(result, "");

        }

        //字符串转Int
        private void ConvertToIntExt(string minStr, string maxStr, out double minNum, out double maxNum)
        {            
            if(double.TryParse(minStr, out minNum) == false)
            {
                minNum = -1;
            }

            if (double.TryParse(maxStr, out maxNum) == false)
            {
                maxNum = -1;
            }

            if (minNum > -1 && maxNum > -1)
            {
                if (minNum > maxNum)
                {
                    minNum = -1;
                    maxNum = -1;
                }
            }
        }




        [AllowAnonymous]
        [Description("API-低价内容")]
        public IHttpActionResult ttGetBuildingModel([FromBody]LowPriceHouses entity)
        {

            var model = LowPriceHousesContract.Entities.Where(m => m.Id == entity.Id).FirstOrDefault();
            var lphbm = LowPriceHouseBuildingsContract.GetByKey(model.LowPriceHouseBuildingID);

            if (model != null)
            {
                ExtMethod.HandleModelValue<LowPriceHouses>(model);//处理null
                ExtMethod.HandleModelValue<LowPriceHouseBuildings>(lphbm);//处理null

                var query = new LowPriceHouseInfoModel();

                //基本信息
                query.BaseInfo = model;

                //价格
                query.CostPrice = (model.CostPrice / 10000m).ToString("F2") + "万元";
                query.LowPrice = (model.LowPrice / 10000m).ToString("F2") + "万元";

                //小区信息
                query.BuildingInfo = lphbm;

                //区域名称
                query.AreaName = (from m1 in AreaContract.Entities where m1.Id == lphbm.AreaID select m1.Name).FirstOrDefault();
                query.AreaName = query.AreaName == null ? "无" : query.AreaName;

                //是否置顶
                var topModel = BuildingTopContract.Entities.Where(b => b.UnionID == model.Id && b.UnionModule == (entity.GroupID + 1) && DateTime.Now > b.BeginTime && DateTime.Now < b.EndTime && !b.IsDeleted).FirstOrDefault();
                query.IsTop = topModel == null ? 0 : 1;//是否置顶


                //封面集合
                var tempList = (from m1 in ImagesContract.Entities where m1.GroupID == 4 && m1.InterfixID == model.Id && m1.IsDeleted == false orderby m1.Id select (m1.ImagePath + m1.FileName));
                query.ImageList = tempList.Select(m => (m == null) ? "" : m.Replace(@"\", "/")).ToList();//图片路径

                //住宅类别
                query.ResidenceType = model.ResidenceType == null ? "无" : model.ResidenceType;//DictionaryContract.Entities.Where(m => m.Id == model.ResidenceType).Select(m => m.Value).FirstOrDefault();
                //query.ResidenceType = query.ResidenceType == null ? "" : query.ResidenceType;

                //房屋类型
                query.BuildingsType = model.BuildingsType == null ? "无" : model.BuildingsType;//DictionaryContract.Entities.Where(m => m.Id == model.BuildingsType).Select(m => m.Value).FirstOrDefault();
                //query.BuildingsType = query.BuildingsType == null ? "" : query.BuildingsType;

                //朝向
                query.Orientations = model.Orientations == null ? "无" : model.Orientations;//DictionaryContract.Entities.Where(m => m.Id == model.Orientations).Select(m => m.Value).FirstOrDefault();
                //query.Orientations = query.Orientations == null ? "" : query.Orientations;

                //房房源负责人
                var staffModel = StaffContract.Entities.Where(m => m.Id == model.StationedStaffID).FirstOrDefault();
                if (staffModel == null)
                {
                    staffModel = new Staff();
                }
                ExtMethod.HandleModelValue<Staff>(staffModel);//处理null
                query.StationedStaff = staffModel;

                //分享信息
                query.HeadTitle = lphbm.Name;
                query.ViceTitle = lphbm.Name;
                query.SharedInfo = model.Remark;
                query.SharedIcon = "";
                query.SharedURL = CommonInof.GetUrl() + "LowPriceHouse/LowPriceHouses/mmBuildingModel?Id=" + entity.Id;
                query.BackUp = "";


                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }


        //报备流程====================================================================================================

        [Description("API-新建报备订单")]
        public IHttpActionResult ttInsertRunningsModel([FromBody]RunningsParamsModel entity)
        {

            if (entity == null)
            {
                var result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }

            try
            {
                //获取UserID
                int userid = BaseWebApiExt.GetUserIDByToken();

                //获取相关信息
                var userModel = UsersContract.GetByKey(userid);//经纪人
                var lowPriceHousesModel = LowPriceHousesContract.GetByKey(entity.BuildingID);//楼盘
                var intermediaryModel = IntermediaryContract.GetByKey(userModel.IntermediaryID);//中介
                var customerModel = CustomerContract.GetByKey(entity.CustomerID);//客户
                var customerPhoneModel = CustomerPhoneContract.GetByKey(entity.CustomerPhoneID);//客户电话
                var intermediaryStaffModel = IntermediaryStaffContract.Entities.Where(m => m.IntermediaryID == userModel.IntermediaryID && m.ModuleID == 1).FirstOrDefault();//低价房销售


                LowPriceHouseRunnings model = new LowPriceHouseRunnings();
                model.LowPriceHouseID = lowPriceHousesModel.Id;
                model.BuildingName = LowPriceHouseBuildingsContract.GetByKey(lowPriceHousesModel.LowPriceHouseBuildingID).Name;
                model.IntermediaryID = intermediaryModel.Id;
                model.IntermediaryName = intermediaryModel.Name;
                model.UserID = userid;
                model.UserName = userModel.Name;
                model.UserPhone = userModel.Phone;
                model.CustomerID = customerModel.Id;
                model.CustomerName = customerModel.Name;
                model.CustomerPhone = customerPhoneModel.Phone;
                model.FilingTime = DateTime.Now;
                model.OriginStaffID = lowPriceHousesModel.MediumOfCommunicationStaffID;//渠道人员ID
                model.SellStaffID = intermediaryStaffModel.StaffID;//销售人员ID
                model.StationedStaffID = lowPriceHousesModel.StationedStaffID;
                model.AgentID = lowPriceHousesModel.AgentID;
                model.GroupID = lowPriceHousesModel.GroupID;
                model.Area = lowPriceHousesModel.Area;
                model.LowPrice = lowPriceHousesModel.LowPrice;
                model.NegotiatedPrice = lowPriceHousesModel.NegotiatedPrice;
                model.HouseNumber = lowPriceHousesModel.HouseNumber;
                //时间初始化
                model.FilingAuditingTime = DateTime.Now;
                model.BandSawTime = DateTime.Now;
                model.SubscribeTime = DateTime.Now;
                model.DownPaymentTime = DateTime.Now;
                model.PutOnRecordTime = DateTime.Now;
                model.CompleteTime = DateTime.Now;
                model.ReturnHouseTime = DateTime.Now;
                model.ReturnHouseAuditingTime = DateTime.Now;
                
                model.State = 1;
                model.ReturnState = 1;

                int count = LowPriceHouseRunningsContract.Insert(model);

                if (count > 0)
                {
                    var result = new AjaxResult("添加成功", AjaxResultType.Success);
                    return Token(result, "");
                }
                else
                {
                    var result = new AjaxResult("添加失败", AjaxResultType.Error);
                    return Token(result, "");
                }
            }
            catch (Exception ex)
            {

                var result = new AjaxResult("添加失败: " + ex.Message, AjaxResultType.Error);
                return Token(result, "");
            }
        }


        [Description("API-获取报备列表")]
        public IHttpActionResult ttGetRunningsList([FromBody]RunningsListModel entity)
        {
            //获取UserID
            int userid = BaseWebApiExt.GetUserIDByToken();

            var query = LowPriceHouseRunningsContract.Entities.Where(m => m.UserID == userid);

            //分组筛选
            if (entity.GroupID > 0)
            {
                query = LowPriceHouseRunningsContract.Entities.Where(m => m.GroupID == entity.GroupID);
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.FilingTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<LowPriceHouseRunnings>().AsQueryable();


            List<RunningsListShowModel> list = new List<RunningsListShowModel>();

            foreach (var item in query)
            {
                var temp = new RunningsListShowModel();
                temp.Id = item.Id;
                temp.CustomerName = item.CustomerName;
                temp.CustomerPhone = item.CustomerPhone;
                temp.BuildingName = item.BuildingName;
                temp.UserName = item.UserName;

                //1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成 
                switch (item.State)
                {
                    case 1:
                        temp.State = "报备待审";
                        temp.OperTime = item.FilingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 2:
                        temp.State = "报备通过";
                        temp.OperTime = item.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 3:
                        temp.State = "报备驳回";
                        temp.OperTime = item.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 4:
                        temp.State = "已带看";
                        temp.OperTime = item.BandSawTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 5:
                        temp.State = "已交订金";
                        temp.OperTime = item.SubscribeTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 6:
                        temp.State = "已付首款";
                        temp.OperTime = item.DownPaymentTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 7:
                        temp.State = "已备案";
                        temp.OperTime = item.PutOnRecordTime.ToString("yy-MM-dd HH:mm");
                        break;
                    case 8:
                        temp.State = "已完成";
                        temp.OperTime = item.CompleteTime.ToString("yy-MM-dd HH:mm");
                        break;
                    default:
                        temp.State = "";
                        temp.OperTime = "";
                        break;
                }

                //退房
                if (item.ReturnState == 2)
                {
                    temp.State = "退房待审";
                    temp.OperTime = item.ReturnHouseTime.ToString("yy-MM-dd HH:mm");
                }
                if (item.ReturnState == 3)
                {
                    temp.State = "已退房";
                    temp.OperTime = item.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm");
                }

                list.Add(temp);
            }


            var result = new AjaxResultRow("成功", AjaxResultType.Success, list, total);
            return Token(result, "");

        }


        [Description("API-查看报备订单")]
        public IHttpActionResult ttGetRunningModel([FromBody]LowPriceHouseRunnings entity)
        {

            var model = LowPriceHouseRunningsContract.GetByKey(entity.Id);

            //记录状态 State： 1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成 
            //退房状态 ReturnState: 1 默认 2 退房待审 3 已退房
            //模板选择： 1 报备+通过 2 报备+未通过 3 带看 4 完成
            //图标形状： 1 进行中，橘黄色 2 已完成，绿色 3 等待，灰色 4 拒绝，红色
            //颜色值： 橘黄色=#F57035 绿色=#3AB394 灰色 =#B3B3B3 红色=#F40001

            if (model != null)
            {
                ExtMethod.HandleModelValue<LowPriceHouseRunnings>(model);//处理null

                var query = new LowPriceHouseRunningsInfoModel();
                query.Id = model.Id;
                query.BuildingName = model.BuildingName;
                query.UserName = model.UserName;
                query.UserPhone = model.UserPhone;
                query.CustomerName = model.CustomerName;
                query.CustomerPhone = model.CustomerPhone;
                query.State = model.State;

                query.LowPriceHouseRunningsInfoShowList = new List<LowPriceHouseRunningsInfoShowModel>();//流水步骤集合

                #region 1 报备

                var FilingModel = new LowPriceHouseRunningsInfoShowModel();
                FilingModel.SortID = 1;

                switch (model.State)
                {
                    case 1://报备待审
                        FilingModel.StyleID = 1;//模板1
                        FilingModel.ModuleName = "报备";
                        FilingModel.ModuleNameColor = "#F57035";//橘黄色
                        FilingModel.ModuleIcon = 1;//进行中
                        FilingModel.ModuleIconColor = "#F57035";//橘黄色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "等待审核";
                        FilingModel.ViceTitleColor = "#F57035";//橘黄色
                        break;
                    case 3://报备驳回
                        FilingModel.StyleID = 2;//模板2
                        FilingModel.ModuleName = "报备";
                        FilingModel.ModuleNameColor = "#F40001";//红色
                        FilingModel.ModuleIcon = 4;//拒绝
                        FilingModel.ModuleIconColor = "#F40001";//红色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "审核未通过";
                        FilingModel.ViceTitleColor = "#F40001";//红色
                        FilingModel.FilingAuditingRemark = model.FilingAuditingRemark == null ? "无" : model.FilingAuditingRemark;//报备审核说明
                        break;
                    case 2://报备通过
                    case 4://已带看
                    case 5://已交订金
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        FilingModel.StyleID = 1;//模板1
                        FilingModel.ModuleName = "报备";
                        FilingModel.ModuleNameColor = "#3AB394";//绿色
                        FilingModel.ModuleIcon = 2;//已完成
                        FilingModel.ModuleIconColor = "#3AB394";//绿色
                        FilingModel.Title = "报备客户";
                        FilingModel.OperTime = model.FilingAuditingTime.ToString("yy-MM-dd HH:mm");
                        FilingModel.ViceTitle = "审核通过";
                        FilingModel.ViceTitleColor = "#3AB394";//绿色
                        break;
                }

                query.LowPriceHouseRunningsInfoShowList.Add(FilingModel);

                #endregion

                # region 2 带看

                var BandSawModel = new LowPriceHouseRunningsInfoShowModel();
                BandSawModel.SortID = 2;

                switch (model.State)
                {
                    case 1://报备待审
                    case 3://报备驳回
                        BandSawModel.StyleID = 4;//模板4
                        BandSawModel.ModuleName = "带看";
                        BandSawModel.ModuleNameColor = "#B3B3B3";//灰色
                        BandSawModel.ModuleIcon = 3;//等待
                        BandSawModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 2://报备通过
                        BandSawModel.StyleID = 3;//模板3
                        BandSawModel.ModuleName = "带看";
                        BandSawModel.ModuleNameColor = "#F57035";//橘黄色
                        BandSawModel.ModuleIcon = 1;//进行中
                        BandSawModel.ModuleIconColor = "#F57035";//橘黄色
                        BandSawModel.Title = "可带看";
                        BandSawModel.OperTime = "";//带看时间
                        BandSawModel.ViceTitle = "";
                        BandSawModel.ViceTitleColor = "";
                        BandSawModel.IsCameraButton = 1;//有照相按钮
                        BandSawModel.GroupID = 5;//分组
                        BandSawModel.ImageType = 1;//带看单
                        BandSawModel.ImageRemark = "带看后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        BandSawModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 5 && m1.ImageType == 1 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//带看图片集合
                        BandSawModel.IsViewButton = 1;//有查看按钮
                        BandSawModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        BandSawModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                    case 4://已带看
                    case 5://已交订金
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        BandSawModel.StyleID = 3;//模板3
                        BandSawModel.ModuleName = "带看";
                        BandSawModel.ModuleNameColor = "#3AB394";//绿色
                        BandSawModel.ModuleIcon = 2;//已完成
                        BandSawModel.ModuleIconColor = "#3AB394";//绿色
                        BandSawModel.Title = "已带看";
                        BandSawModel.OperTime = model.BandSawTime.ToString("yyyy-MM-dd HH:mm");//带看时间
                        BandSawModel.ViceTitle = "";
                        BandSawModel.ViceTitleColor = "";
                        BandSawModel.IsCameraButton = 1;//有照相按钮
                        BandSawModel.GroupID = 5;//分组
                        BandSawModel.ImageType = 1;//带看单
                        BandSawModel.ImageRemark = "带看后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        BandSawModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 5 && m1.ImageType == 1 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//带看图片集合
                        BandSawModel.IsViewButton = 1;//有查看按钮
                        BandSawModel.ViewButtonText = "查看\"客户带看单\"范例";//查看按钮文本
                        BandSawModel.ViewButtonValue = "";//查看按钮链接地址
                        break;
                }

                query.LowPriceHouseRunningsInfoShowList.Add(BandSawModel);

                #endregion

                #region 3 认购

                var SubscribeModel = new LowPriceHouseRunningsInfoShowModel();
                SubscribeModel.ModuleName = "认购";
                switch (model.State)
                {
                    case 1://报备待审
                    case 2://报备通过
                    case 3://报备驳回                    
                        SubscribeModel.StyleID = 4;//模板4         
                        SubscribeModel.ModuleNameColor = "#B3B3B3";//灰色
                        SubscribeModel.ModuleIcon = 3;//等待
                        SubscribeModel.ModuleIconColor = "#B3B3B3";//灰色                                                                   
                        break;
                    case 4://带看完成 待交定金
                        SubscribeModel.StyleID = 3;//模板3              
                        SubscribeModel.ModuleNameColor = "#F57035";//橘黄色
                        SubscribeModel.ModuleIcon = 1;//进行中
                        SubscribeModel.ModuleIconColor = "#F57035";//橘黄色
                        SubscribeModel.Title = "待交定金";
                        SubscribeModel.OperTime = "";//待交定金没有时间
                        SubscribeModel.ViceTitle = "";//副标题  定金金额  
                        SubscribeModel.ViceTitleColor = "";
                        SubscribeModel.IsCameraButton = 1;//有相机
                        SubscribeModel.GroupID = 5;//分组
                        SubscribeModel.ImageType = 2;//成交确认单                        
                        SubscribeModel.ImageRemark = "请上传\"认购确认单\"照片！";
                        SubscribeModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 5 && m1.ImageType == 2 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//成交图片集合
                        FilingModel.IsViewButton = 0;//没有查看按钮
                        break;
                    case 5://已交定金
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        SubscribeModel.StyleID = 3;//模板3
                        SubscribeModel.ModuleNameColor = "#3AB394";//绿色
                        SubscribeModel.ModuleIcon = 2;//已完成
                        SubscribeModel.ModuleIconColor = "#3AB394";//绿色
                        SubscribeModel.Title = "已付定金";
                        SubscribeModel.OperTime = model.SubscribeTime.ToString("yy-MM-dd HH:mm"); ;//已付定金时间                        
                        SubscribeModel.ViceTitle = (model.BargainMoney / 10000).ToString("0.00") + "万元";//副标题  定金金额  
                        SubscribeModel.ViceTitleColor = "";
                        SubscribeModel.IsCameraButton = 0;//没有相机
                        SubscribeModel.GroupID = 5;//分组
                        SubscribeModel.ImageType = 2;//成交确认单
                        SubscribeModel.ImageRemark = "请上传\"认购确认单\"照片！";
                        SubscribeModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 5 && m1.ImageType == 2 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//成交图片集合
                        SubscribeModel.IsViewButton = 0;//没有查看按钮
                        break;
                }

                query.LowPriceHouseRunningsInfoShowList.Add(SubscribeModel);

                #endregion

                #region 4 首付

                var DownPaymentModel = new LowPriceHouseRunningsInfoShowModel();
                DownPaymentModel.SortID = 4;//排序
                DownPaymentModel.ModuleName = "首付";

                switch (model.State)
                {
                    case 1://报备待审                   
                    case 2://报备通过
                    case 3://报备驳回                  
                    case 4://已带看
                        DownPaymentModel.StyleID = 4;//模板4            
                        DownPaymentModel.ModuleNameColor = "#B3B3B3";//灰色
                        DownPaymentModel.ModuleIcon = 3;//等待
                        DownPaymentModel.ModuleIconColor = "#B3B3B3";//灰色
                        break;
                    case 5://已付定金  
                        if (model.ReturnState.Equals(3))//已退房
                        {
                            DownPaymentModel.StyleID = 1;//模板1
                            DownPaymentModel.ModuleNameColor = "#F40001";//红色
                            DownPaymentModel.ModuleIcon = 4;//拒绝
                            DownPaymentModel.ModuleIconColor = "#F40001";//红色
                            DownPaymentModel.Title = "已退房";
                            DownPaymentModel.OperTime = model.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm"); ;//退房审核时间
                            DownPaymentModel.ViceTitle = "";//副标题  没有内容
                            DownPaymentModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        else//正常
                        {
                            DownPaymentModel.StyleID = 1;//模板1
                            DownPaymentModel.ModuleNameColor = "#F57035";//橘黄色
                            DownPaymentModel.ModuleIcon = 1;//进行中
                            DownPaymentModel.ModuleIconColor = "#F57035";//橘黄色
                            DownPaymentModel.Title = "待交首付";
                            DownPaymentModel.OperTime = "";//待交首付没有时间
                            DownPaymentModel.ViceTitle = "";//副标题  没有内容
                            DownPaymentModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        break;
                    case 6://已付首款
                    case 7://已备案
                    case 8://已完成
                        DownPaymentModel.StyleID = 1;//模板1
                        DownPaymentModel.ModuleNameColor = "#3AB394";//绿色
                        DownPaymentModel.ModuleIcon = 2;//已完成
                        DownPaymentModel.ModuleIconColor = "#3AB394";//绿色
                        DownPaymentModel.Title = "已交首付";
                        DownPaymentModel.OperTime = model.DownPaymentTime.ToString("yy-MM-dd HH:mm"); ;//首付时间
                        DownPaymentModel.ViceTitle = (model.DownPaymentMoney / 10000).ToString("0.00") + "万元";//副标题  已交首付金额   
                        DownPaymentModel.ViceTitleColor = "#F57035";//副标题  橘黄色                      
                        break;
                }

                query.LowPriceHouseRunningsInfoShowList.Add(DownPaymentModel);

                #endregion

                #region 5 备案

                var PutOnRecordModel = new LowPriceHouseRunningsInfoShowModel();
                PutOnRecordModel.ModuleName = "备案";
                PutOnRecordModel.SortID = 5;

                switch (model.State)
                {
                    case 1://报备待审
                    case 2://报备通过
                    case 3://报备驳回
                    case 4://已带看
                    case 5://已交订金
                        PutOnRecordModel.StyleID = 4;//模板4                        
                        PutOnRecordModel.ModuleNameColor = "#B3B3B3";//灰色
                        PutOnRecordModel.ModuleIcon = 3;//等待
                        PutOnRecordModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 6://已付首款
                        if (model.ReturnState.Equals(3))//已退房
                        {
                            PutOnRecordModel.StyleID = 1;//模板1
                            PutOnRecordModel.ModuleNameColor = "#F40001";//红色
                            PutOnRecordModel.ModuleIcon = 4;//拒绝
                            PutOnRecordModel.ModuleIconColor = "#F40001";//红色
                            PutOnRecordModel.Title = "已退房";
                            PutOnRecordModel.OperTime = model.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm"); ;//退房审核时间
                            PutOnRecordModel.ViceTitle = "";//副标题  没有内容
                            PutOnRecordModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        else//正常
                        {
                            PutOnRecordModel.StyleID = 3;//模板3
                            PutOnRecordModel.ModuleNameColor = "#F57035";//橘黄色
                            PutOnRecordModel.ModuleIcon = 1;//进行中
                            PutOnRecordModel.ModuleIconColor = "#F57035";//橘黄色
                            PutOnRecordModel.Title = "待备案";
                            PutOnRecordModel.OperTime = "";//备案时间
                            PutOnRecordModel.ViceTitle = "";
                            PutOnRecordModel.ViceTitleColor = "";
                            PutOnRecordModel.IsCameraButton = 1;//有照相按钮
                            PutOnRecordModel.GroupID = 5;//分组
                            PutOnRecordModel.ImageType = 3;//备案合同
                            PutOnRecordModel.ImageRemark = "请上传\"备案合同\"照片!";
                            PutOnRecordModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 5 && m1.ImageType == 3 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//备案图片集合
                            PutOnRecordModel.IsViewButton = 0;//没有查看按钮
                        }
                        break;
                    case 7://已备案
                    case 8://已完成
                        PutOnRecordModel.StyleID = 3;//模板3
                        PutOnRecordModel.ModuleNameColor = "#3AB394";//绿色
                        PutOnRecordModel.ModuleIcon = 2;//已完成
                        PutOnRecordModel.ModuleIconColor = "#3AB394";//绿色
                        PutOnRecordModel.Title = "已备案";
                        PutOnRecordModel.OperTime = model.PutOnRecordTime.ToString("yy-MM-dd HH:mm");//备案时间
                        PutOnRecordModel.ViceTitle = "";
                        PutOnRecordModel.ViceTitleColor = "";
                        PutOnRecordModel.IsCameraButton = 1;//有照相按钮
                        PutOnRecordModel.GroupID = 5;//分组
                        PutOnRecordModel.ImageType = 3;//带看单
                        PutOnRecordModel.ImageRemark = "带看后请上传照片，\"客户带看单\"照片为必传照片，带看单必需有置业顾问、经纪人、项目经理签字，其他照片可以是\"客户与售楼员合影\"、\"客户与经纪人合影\"等等!";
                        PutOnRecordModel.ImageList = ImagesContract.Entities.Where(m1 => m1.GroupID == 5 && m1.ImageType == 3 && m1.InterfixID == model.Id && m1.IsDeleted == false).ToList();//备案图片集合
                        PutOnRecordModel.IsViewButton = 0;//没有查看按钮
                        break;
                }

                query.LowPriceHouseRunningsInfoShowList.Add(PutOnRecordModel);

                #endregion

                #region 6 完成

                var CompleteModel = new LowPriceHouseRunningsInfoShowModel();
                CompleteModel.ModuleName = "完成";
                CompleteModel.SortID = 6;

                switch (model.State)
                {
                    case 1://报备待审
                    case 2://报备通过
                    case 3://报备驳回
                    case 4://已带看
                    case 5://已交订金
                    case 6://已付首款
                        CompleteModel.StyleID = 4;//模板4                        
                        CompleteModel.ModuleNameColor = "#B3B3B3";//灰色
                        CompleteModel.ModuleIcon = 3;//等待
                        CompleteModel.ModuleIconColor = "#B3B3B3";//灰色                        
                        break;
                    case 7://已备案
                    case 8://已完成
                        if (model.ReturnState.Equals(3))//已退房
                        {
                            CompleteModel.StyleID = 1;//模板1
                            CompleteModel.ModuleNameColor = "#F40001";//红色
                            CompleteModel.ModuleIcon = 4;//拒绝
                            CompleteModel.ModuleIconColor = "#F40001";//红色
                            CompleteModel.Title = "已退房";
                            CompleteModel.OperTime = model.ReturnHouseAuditingTime.ToString("yy-MM-dd HH:mm"); ;//退房审核时间
                            CompleteModel.ViceTitle = "";//副标题  没有内容
                            CompleteModel.ViceTitleColor = "";//副标题  没有颜色 
                        }
                        else//正常
                        {
                            CompleteModel.StyleID = 4;//模板4
                            CompleteModel.ModuleNameColor = "#3AB394";//绿色
                            CompleteModel.ModuleIcon = 2;//已完成
                            CompleteModel.ModuleIconColor = "#3AB394";//绿色
                        }
                        break;
                }

                query.LowPriceHouseRunningsInfoShowList.Add(CompleteModel);

                #endregion


                //跟进信息====================================================================================================

                query.MessageBoardsShowList = (from m in MessageBoardsContract.Entities
                                               join n in StaffContract.Entities
                                               on m.StaffID equals n.Id into tempb
                                               from b in tempb.DefaultIfEmpty()
                                               where m.MessageBoardsType == 4 && m.InterfixID == model.Id && m.IsDeleted == false
                                               select new
                                               {
                                                   StaffName = b.Name == null ? "" : b.Name,
                                                   Content = m.Content,
                                                   CreatedTime = m.CreatedTime
                                               }).ToList()
                                               .Select(m => new MessageBoardsShowModel
                                               {
                                                   StaffName = m.StaffName,
                                                   Content = m.Content,
                                                   CreatedTime = m.CreatedTime.ToString("yy-MM-dd HH:mm")
                                               }).ToList();//跟进信息集合


                //佣金====================================================================================================


                //佣金计算
                decimal totalAmount = 0;//应得佣金
                decimal taxAmount = 0;//税款
                decimal achieveAmount = 0;//已结佣金                
                decimal unAchieveAmount = 0;//未结佣金
                int brokerageState = 1;//佣金流水状态

                //应得佣金 参照表BrokerageType
                var brokerageRunningsModel = BrokerageRunningsContract.Entities.Where(m => m.ModuleID == 2 && m.RunningsID == model.Id && m.BrokerageTypeID == 7).FirstOrDefault();
                if (brokerageRunningsModel != null)
                {
                    totalAmount = brokerageRunningsModel.Amount;
                    taxAmount = brokerageRunningsModel.Tax;
                    brokerageState = brokerageRunningsModel.State;

                    var brokerageSettleAccountsRunningsList = BrokerageSettleAccountsRunningsContract.Entities.Where(m => m.BrokerageRunningsID == brokerageRunningsModel.Id).ToList();
                    foreach (var item in brokerageSettleAccountsRunningsList)
                    {
                        achieveAmount += item.Amount;
                    }
                }
                unAchieveAmount = totalAmount - taxAmount - achieveAmount;

                query.TotalAmount = totalAmount.ToString("0.00") + "元";
                query.TaxAmount = taxAmount.ToString("0.00") + "元";
                query.AchieveAmount = achieveAmount.ToString("0.00") + "元";
                query.UnAchieveAmount = unAchieveAmount.ToString("0.00") + "元";
                switch (brokerageState)
                {
                    case 0:
                    case 1:
                        query.BrokerageState = 2;
                        break;
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                        query.BrokerageState = 1;
                        break;
                }

                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");

            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }

    }
}
